'''
优化上面的程序，文件路径文本框和选择文件按钮，要跟随界面的拉升和缩小进行伸缩。
'''
import os
import tkinter as tk
from tkinter import filedialog

class FileSplitter:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("文件切割小工具")

        # 文件路径文本框和选择文件按钮
        file_frame = tk.Frame(self.root)
        file_frame.pack(fill=tk.X, expand=True)

        self.file_path_label = tk.Label(file_frame, text="文件路径：")
        self.file_path_label.pack(side=tk.LEFT,fill=tk.X)

        self.file_path_entry = tk.Entry(file_frame, width=50)
        self.file_path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)

        self.file_button = tk.Button(file_frame, text="选择文件", command=self.select_file)
        self.file_button.pack(side=tk.LEFT)

        # 进度文本框
        self.progress_text = tk.Text(self.root, height=10, width=50)
        self.progress_text.pack(fill=tk.BOTH, expand=True)

        # 开始切割文件按钮
        self.start_button = tk.Button(self.root, text="开始切割文件", command=self.start_split)
        self.start_button.pack(fill=tk.X, expand=True)


    def select_file(self):
        file_path = filedialog.askopenfilename()
        self.file_path_entry.delete(0, tk.END)
        self.file_path_entry.insert(tk.END, file_path)


    def start_split(self):
        file_path = self.file_path_entry.get()
        if not file_path:
            return

        # 获取文件大小
        file_size = os.path.getsize(file_path)

        # 设置切割块大小
        block_size = 1024 * 1024  # 1MB

        # 计算切割块数量
        block_count = file_size // block_size + 1

        # 进度条
        progress = 0

        # 计算每10%的块数
        block_per_ten_percent = block_count // 10 + 1

        # 切割文件
        with open(file_path, "rb") as f:
            # 切割文件, 每10%的块数更新一次进度条
            for i in range(block_count):
                block_data = f.read(block_size)
                with open(f"{file_path}_{i+1}.part", "wb") as part_f:
                    part_f.write(block_data)

                # 更新进度条
                if i % block_per_ten_percent == 0:
                    progress += 10
                    self.progress_text.insert(tk.END, f"{progress}%\n")
                    self.progress_text.see(tk.END)

        self.progress_text.insert(tk.END, "切割完成\n")
        self.progress_text.see(tk.END)

    def run(self):
        self.root.mainloop()

if __name__ == "__main__":
    app = FileSplitter()
    app.run()
